import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, IOException {
        // 开始运行
        runSimulation("record.txt");
    }

    private static void runSimulation(String filename) throws InterruptedException, IOException {
        CDStore store = new CDStore();
        Logger logger = Logger.getInstance();

        Thread restockThread = new Thread(new RestockThread(store, logger));
        restockThread.start();

        List<Thread> threads = new ArrayList<>();

        // 创建2个销售线程
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(new SaleThread(store, logger, restockThread));
            t.start();
            threads.add(t);
        }

        // 创建2个租赁线程
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(new RentThread(store, logger));
            t.start();
            threads.add(t);
        }

        // 运行2分钟
        Thread.sleep(120000);

        // 停止所有线程
        restockThread.interrupt();
        for (Thread t : threads) {
            t.interrupt();
        }

        // 等待线程终止
        restockThread.join();
        for (Thread t : threads) {
            t.join();
        }

        // 保存日志
        logger.saveToFile(filename);
    }
}
